﻿using Dapper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using CommServer.Cache;
using CommServer.Common;
using CommServer.Common.Database;
using CommServer.Network;

namespace CommServer.Controllers
{
    public class ServerController : Controller
    {
        [HttpPost]
        [HttpGet]
        public DbResult<int> Login(string Name, string Pwd)
        {
            DbResult<int> Result = new DbResult<int>();
            try
            {
                using (var conn = DbHelper.GetConn())
                {
                    var user = conn.QueryFirstOrDefault("select * from userinfo where Username=@Username", new { Username = Name });
                    if (user == null)
                    {
                        Result.state = (int)ErrorCode.UserNotExist;
                        Result.errMsg = "用户不存在";
                        return Result;
                    }
                    MD5 md5 = MD5.Create();
                    byte[] PwdMd5 = md5.ComputeHash(Encoding.ASCII.GetBytes(Pwd));
                    if (user.Password != Util.BytesToHex(PwdMd5).ToLower())
                    {
                        Result.state = (int)ErrorCode.PasswordIncorrect;
                        Result.errMsg = "密码不正确";
                        return Result;
                    }
                    HttpContext.Session.Set("UserId", BitConverter.GetBytes(user.Id));
                    HttpContext.Session.Set("UserRole", BitConverter.GetBytes(user.Role));
                    
                    Result.data = user.Id;
                }
                Result.state = 0;
            }
            catch (Exception ex)
            {
                Result.errMsg = ex.Message;
            }

            return Result;
        }

        [HttpGet]
        public DbData<dynamic> GetCollects()
        {
            DbData<dynamic> Result = new DbData<dynamic>();
            try
            {
                if (!HttpContext.Session.TryGetValue("UserId", out byte[] UserId))
                {
                    Result.state = (int)DbFailType.UserNotLogin;
                    Result.errMsg = "用户未登录";
                    return Result;
                }
                string sql = "select c.*,d.SimSn,d.SimNo,d.SVer from userinfo A " +
                                " inner join plantinfo B on A.PlantNo = b.PlantNo " +
                                " inner join collector C on b.PlantNo = c.PlantSn" +
                                " inner join kd_rtuinfo d on c.PlantUnit = d.RtuSn" +
                                " where A.id = " + BitConverter.ToInt32(UserId, 0);
                using (var conn = DbHelper.GetConn())
                {
                    Result.data = conn.Query(sql).ToList();
                }
                Result.state = 0;
            }
            catch (Exception ex)
            {
                Result.errMsg = ex.Message;
            }

            return Result;
        }

        [HttpGet]
        public DbData<dynamic> GetDevices()
        {
            DbData<dynamic> Result = new DbData<dynamic>();
            try
            {
                if (!HttpContext.Session.TryGetValue("UserId", out byte[] UserId))
                {
                    Result.state = (int)DbFailType.UserNotLogin;
                    Result.errMsg = "用户未登录";
                    return Result;
                }
                string sql = "select D.* as KdSimNo from userinfo A " +
                                " inner join plantinfo B on A.PlantNo = B.PlantNo " +
                                " inner join collector C on B.PlantNo = C.PlantSn" +
                                " inner join deviceinfo D on C.PlantSn = C.PlantSn and c.PlantUnit = d.PlantUnit " +
                                " inner join kd_rtuinfo E on C.PlantUnit = E.RtuSn" +
                                " where A.id = " + BitConverter.ToInt32(UserId, 0);
                using (var conn = DbHelper.GetConn())
                {
                    Result.data = conn.Query(sql).ToList();
                }
                Result.state = 0;
            }
            catch (Exception ex)
            {
                Result.errMsg = ex.Message;
            }

            return Result;
        }

        [HttpGet]
        public DbData<dynamic> GetStations()
        {
            DbData<dynamic> Result = new DbData<dynamic>();
            try
            {
                if (!HttpContext.Session.TryGetValue("UserId", out byte[] UserId))
                {
                    Result.state = (int)DbFailType.UserNotLogin;
                    Result.errMsg = "用户未登录";
                    return Result;
                }
                string sql = "select b.PlantName, c.* from userinfo A " +
                                " inner join plantinfo B on A.PlantNo = b.PlantNo " +
                                " inner join plantsummaryinstance C on b.PlantNo = c.PlantSn" +
                                " where A.id = " + BitConverter.ToInt32(UserId, 0);
                using (var conn = DbHelper.GetConn())
                {
                    Result.data = conn.Query(sql).ToList();
                }
                Result.state = 0;
            }
            catch (Exception ex)
            {
                Result.errMsg = ex.Message;
            }

            return Result;
        }

        [HttpPost]
        public DbResult SetLogOutput(bool LogInfo, bool LogDebug, bool LogConsole)
        {
            DbResult Result = new DbResult();
            try
            {
                if (!HttpContext.Session.TryGetValue("UserId", out byte[] UserId))
                {
                    Result.state = (int)DbFailType.UserNotLogin;
                    Result.errMsg = "用户未登录";
                    return Result;
                }
                Log.SetOptions(Convert.ToInt32(LogInfo), Convert.ToInt32(LogDebug), Convert.ToInt32(LogConsole));
                Result.state = 0;
            }
            catch (Exception ex)
            {
                Result.errMsg = ex.Message;
            }

            return Result;
        }

        [HttpPost]
        public DbResult ImportKdCollect(IFormFile file)
        {
            DbResult Result = new DbResult();
            if (!HttpContext.Session.TryGetValue("UserId", out byte[] UserId))
            {
                Result.state = (int)DbFailType.UserNotLogin;
                Result.errMsg = "用户未登录";
                return Result;
            }
            try
            {
                List<string> Lines = new List<string>();
                using (Stream stream = file.OpenReadStream())
                {
                    StreamReader Reader = new StreamReader(stream);
                    string Line;
                    while ((Line = Reader.ReadLine()) != null)
                    {
                        Lines.Add(Line);
                    }
                }
                string sql = "";
                for (int i = 0; i < Lines.Count; i++)
                {
                    string[] Cols = Lines[i].Split(new char[] { ',' });
                    if (Cols.Length != 4)
                    {
                        Result.errMsg = "文件格式不正确,行数：" + i + 1;
                        return Result;
                    }
                    sql += "('" + Cols[0] + "','" + Cols[1] + "','" + Cols[2] + "','" + Cols[3] + "'),";
                }
                if (sql.Length > 0)
                {
                    sql = sql.Substring(0, sql.Length - 1);
                }
                sql = "insert into KD_RtuInfo values" + sql;
                sql += " on duplicate key update";
                sql += " RtuSN=values(RtuSN),";
                sql += " SimSN=values(SimSN),";
                sql += " SimNo=values(SimNo),";
                sql += " Sver=values(Sver)";
                using (var conn = DbHelper.GetConn())
                {
                    conn.Execute(sql);
                }
                CacheDevices.Load();
            }
            catch (Exception ex)
            {
                Result.errMsg = ex.Message;
            }

            return Result;
        }
    }
}
